<style lang="less" scoped>
@import "./user.less";
</style>
<template>
    <div>
        <Row>
            <!-- <Col span="24">
                <Card style="margin-bottom: 10px">
                    <Form inline>
                        <FormItem style="margin-bottom: 0">
                            <Select v-model="searchConf.status" clearable placeholder='请选择状态' style="width:100px">
                                <Option :value="1">启用</Option>
                                <Option :value="0">禁用</Option>
                            </Select>
                        </FormItem>
                        <FormItem style="margin-bottom: 0">
                            <Select v-model="searchConf.type" clearable placeholder="请选择类别" style="width:100px">
                                <Option :value="1">用户账号</Option>
                                <Option :value="2">真实姓名</Option>
                            </Select>
                        </FormItem>
                        <FormItem style="margin-bottom: 0">
                            <Input v-model="searchConf.keywords" placeholder=""></Input>
                        </FormItem>
                        <FormItem style="margin-bottom: 0">
                            <Button type="primary" @click="search">查询/刷新</Button>
                        </FormItem>
                    </Form>
                </Card>
            </Col> -->
        </Row>
        <Row>
            <Col span="24">
                <Card>
                    <p slot="title" style="height: 32px">
                        <Button type="primary" @click="alertAdd" icon="plus-round">新增</Button>
                    </p>
                    <div>
                        <Table :columns="columnsList" :data="tableData" border disabled-hover></Table>
                    </div>
                    <div class="margin-top-15" style="text-align: center">
                        <Page :total="tableShow.listCount" :current="tableShow.currentPage"
                              :page-size="tableShow.pageSize" @on-change="changePage"
                              @on-page-size-change="changeSize" show-elevator show-sizer show-total></Page>
                    </div>
                </Card>
            </Col>
        </Row>
        <Modal v-model="modalSetting.show" width="668" :styles="{top: '30px'}" @on-visible-change="doCancel">
            <p slot="header" style="color:#2d8cf0;">
                <Icon type="information-circled"></Icon>
                <span>{{formItem.id ? '编辑' : '新增'}}用户</span>
            </p>
            <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="80">
                <FormItem label="用户账号" prop="username">
                    <Input v-model="formItem.username" placeholder="请输入账号"></Input>
                </FormItem>
                <FormItem label="真实姓名" prop="nickname">
                    <Input v-model="formItem.nickname" placeholder="请输入账号"></Input>
                </FormItem>
                <FormItem label="用户密码" prop="password">
                    <Input v-model="formItem.password" type="password" placeholder="用户密码"></Input>
                </FormItem>
                <FormItem label="权限组" prop="groupId">
                    <CheckboxGroup v-model="formItem.groupId">
                        <Checkbox v-for="group in groupList" :key="group.id" :label="group.id + ''">{{ group.title }}</Checkbox>
                    </CheckboxGroup>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancel" style="margin-right: 8px">取消</Button>
                <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
            </div>
        </Modal>
        <Modal v-model="bind.show" width="668" :style="{top:'30px'}" @on-ok="bindUser">
            <Form :model="bindModel" :label-width="80">
                <FormItem label="选择用户" prop="user">
                    <Select v-model="bindModel.user" filterable
                remote
                :remote-method="searchUsers"
                :loading="bind.loading">
                        <Option v-for="item in userList" :key="item.id" :value="item.id" :label="item.name">
                            <div class="list">
                                <div class="avatar">
                                    <img :src="item.avatar">
                                </div>
                                <div class="content">
                                    <span>{{item.name}}</span>
                                    <span>{{item.real_name}}</span>
                                </div>
                            </div>
                        </Option>
                    </Select>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
import axios from "axios";
const editButton = (vm, h, currentRow, index) => {
  return h(
    "Button",
    {
      props: {
        type: "primary"
      },
      style: {
        margin: "0 5px"
      },
      on: {
        click: () => {
          axios.get("user/" + currentRow.id + "/groups").then(response => {
            let res = response.data;
            if (res.code === 200) {
              vm.formItem.groupId = res.data;
              console.log(vm.formItem.groupId);
            } else {
              vm.$Message.error(res.msg);
            }
          });

          vm.formItem.id = currentRow.id;
          vm.formItem.username = currentRow.name;
          vm.formItem.nickname = currentRow.user_name;
          vm.formItem.password = "ApiAdmin";
          axios.get("groups").then(function(response) {
            let res = response.data;
            if (res.code === 200) {
              vm.groupList = res.data.list;
            } else {
              if (res.code === 403) {
                vm.$store.commit("logout", vm);
                vm.$router.push({
                  name: "login"
                });
              } else {
                vm.$Message.error(res.msg);
              }
            }
          });

          // vm.formItem.groupId = currentRow.groupId;
          vm.modalSetting.show = true;
          vm.modalSetting.index = index;
        }
      }
    },
    "编辑"
  );
};
const deleteButton = (vm, h, currentRow, index) => {
  return h(
    "Poptip",
    {
      props: {
        confirm: true,
        title: "您确定要删除这条数据吗? ",
        transfer: true
      },
      on: {
        "on-ok": () => {
          axios.delete("user/" + currentRow.id).then(function(response) {
            currentRow.loading = false;
            if (response.data.code === 200) {
              vm.tableData.splice(index, 1);
              vm.$Message.success(response.data.msg);
            } else {
              vm.$Message.error(response.data.msg);
            }
          });
        }
      }
    },
    [
      h(
        "Button",
        {
          style: {
            margin: "0 5px"
          },
          props: {
            type: "error",
            placement: "top",
            loading: currentRow.isDeleting
          }
        },
        "删除"
      )
    ]
  );
};

export default {
  name: "system_user",
  data() {
    return {
      bind: {
        show: false,
        loading: false
      },
      userList: [],
      bindModel: {
        id: 0,
        user: ""
      },
      columnsList: [
        {
          title: "序号",
          type: "index",
          width: 65,
          align: "center"
        },
        {
          title: "用户账号",
          align: "center",
          key: "name"
        },
        {
          title: "真实姓名",
          align: "center",
          key: "user_name",
          width: 120
        },
        {
          title: "登录次数",
          align: "center",
          key: "login_times",
          width: 90
        },
        {
          title: "最后登录时间",
          align: "center",
          key: "update_time",
          width: 160
        },
        {
          title: "最后登录IP",
          align: "center",
          key: "ip",
          width: 160
        },
        {
          title: "状态",
          align: "center",
          key: "status",
          width: 100
        },
        {
          title: "微信昵称",
          align: "center",
          render:(h,params)=>{
            return h(
              "div",
              {},
              params.row.users ? params.row.users.name : ""
            );
          }
        },
        {
          title: "微信真实名",
          align: "center",
          render:(h,params)=>{
            return h(
              "div",
              {},
              params.row.users ? params.row.users.real_name?params.row.users.real_name:"" : ""
            );
          }
        },
        {
          title: "设置",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  style:{
                      margin:'0 5px'
                    },
                  props: {
                    type: "primary"
                  },
                  on: {
                    click: param => {
                      this.bind.show = true;
                      this.bindModel.id = params.row.id;
                    }
                  }
                },
                "绑定用户"
              ),
              h(
                "Button",
                {
                  style:{
                      margin:'0 5px'
                    },
                  props: {
                    type: "warning",
                    
                  },
                  on: {
                    click: ()=>{
                      axios.post('users/unbind/'+params.row.id).then(response=>{
                        let res = response.data
                        if(res.code == 200){
                          this.$Message.success(res.msg)
                          this.getList()
                        }else{
                          this.$Message.error(res.msg)
                        }
                      })
                    }
                  }
                },
                "解绑用户"
              )
            ]);
          },
          width: 250
        },
        {
          title: "操作",
          align: "center",
          key: "handle",
          width: 175,
          handle: ["edit", "delete"]
        }
      ],
      tableData: [],
      groupList: [],
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      searchConf: {
        type: "",
        keywords: "",
        status: ""
      },
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      formItem: {
        username: "",
        nickname: "",
        password: "",
        groupId: [],
        id: 0
      },
      ruleValidate: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        nickname: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.init();
    this.getList();
  },
  methods: {
    init() {
      let vm = this;
      this.columnsList.forEach(item => {
        if (item.handle) {
          item.render = (h, param) => {
            let currentRowData = vm.tableData[param.index];
            return h("div", [
              editButton(vm, h, currentRowData, param.index),
              deleteButton(vm, h, currentRowData, param.index)
            ]);
          };
        }
        if (item.key === "status") {
          item.render = (h, param) => {
            let currentRowData = vm.tableData[param.index];
            return h(
              "i-switch",
              {
                attrs: {
                  size: "large"
                },
                props: {
                  "true-value": 1,
                  "false-value": 0,
                  value: currentRowData.status
                },
                on: {
                  "on-change": function(status) {
                    axios
                      .patch("user/" + currentRowData.id + "/status/" + status)
                      .then(function(response) {
                        let res = response.data;
                        if (res.code === 200) {
                          vm.$Message.success(res.msg);
                        } else {
                          if (res.code === 403) {
                            vm.$store.commit("logout", vm);
                            vm.$router.push({
                              name: "login"
                            });
                          } else {
                            vm.$Message.error(res.msg);
                            vm.getList();
                          }
                        }
                        vm.cancel();
                      });
                  }
                }
              },
              [
                h(
                  "span",
                  {
                    slot: "open"
                  },
                  "启用"
                ),
                h(
                  "span",
                  {
                    slot: "close"
                  },
                  "禁用"
                )
              ]
            );
          };
        }
      });
    },
    alertAdd() {
      let vm = this;
      axios.get("groups").then(function(response) {
        let res = response.data;
        if (res.code === 200) {
          vm.groupList = res.data.list;
        } else {
          if (res.code === 403) {
            vm.$store.commit("logout", vm);
            vm.$router.push({
              name: "login"
            });
          } else {
            vm.$Message.error(res.msg);
          }
        }
      });
      this.modalSetting.show = true;
    },
    submit() {
      let self = this;
      this.$refs["myForm"].validate(valid => {
        if (valid) {
          self.modalSetting.loading = true;
          if (this.formItem.id === 0) {
            axios.post("user", this.formItem).then(response => {
              if (response.data.code === 200) {
                self.$Message.success(response.data.msg);
              } else {
                self.$Message.error(response.data.msg);
              }
            });
          } else {
            axios
              .put("user/" + this.formItem.id, this.formItem)
              .then(response => {
                if (response.data.code === 200) {
                  self.$Message.success(response.data.msg);
                } else {
                  self.$Message.error(response.data.msg);
                }
              });
          }
          self.getList();
          self.cancel();
        }
      });
    },
    cancel() {
      this.modalSetting.show = false;
    },
    doCancel(data) {
      if (!data) {
        this.formItem.id = 0;
        this.$refs["myForm"].resetFields();
        this.modalSetting.loading = false;
        this.modalSetting.index = 0;
      }
    },
    changePage(page) {
      this.tableShow.currentPage = page;
      this.getList();
    },
    changeSize(size) {
      this.tableShow.pageSize = size;
      this.getList();
    },
    search() {
      this.tableShow.currentPage = 1;
      this.getList();
    },
    getList() {
      let vm = this;
      axios
        .get("user", {
          params: {
            page: vm.tableShow.currentPage,
            size: vm.tableShow.pageSize,
            type: vm.searchConf.type,
            keywords: vm.searchConf.keywords,
            status: vm.searchConf.status
          }
        })
        .then(function(response) {
          let res = response.data;
          if (res.code === 200) {
            vm.tableData = res.data.list;
            vm.tableShow.listCount = res.data.count;
          } else {
            if (res.code === 403) {
              vm.$store.commit("logout", vm);
              vm.$router.push({
                name: "login"
              });
            } else {
              vm.$Message.error(res.msg);
            }
          }
        });
    },
    searchUsers(query) {
      if (query != "") {
        axios
          .get("users/searches", { params: { key: query } })
          .then(response => {
            let res = response.data;
            if (res.code == 200) {
              this.userList = res.data.list;
            } else {
              if (res.code === 403) {
                this.$store.commit("logout", this);
                this.$router.push({
                  name: "login"
                });
              } else {
                this.$Message.error(res.msg);
              }
            }
          });
      }
    },
    bindUser() {
      axios.post("users/bind", this.bindModel).then(response => {
        let res = response.data;
        if (res.code == 200) {
          this.$Message.success(res.msg)
          this.getList()
        } else {
          if (res.code === 403) {
            this.$store.commit("logout", this);
            this.$router.push({
              name: "login"
            });
          } else {
            this.$Message.error(res.msg);
          }
        }
      });
    }
  }
};
</script>
